package com.lib.controller.user;

import com.lib.common.constant.JwtClaimsConstant;
import com.lib.common.properties.JwtProperties;
import com.lib.common.utils.JwtUtils;
import com.lib.pojo.DTO.UserLoginDTO;
import com.lib.pojo.VO.UserLoginVO;
import com.lib.pojo.entity.Result;
import com.lib.pojo.entity.User;
import com.lib.service.UserLoginService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Tag(name = "用户登录接口")
@RequestMapping("/user/login")
@Slf4j
public class UserLoginController {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserLoginService userLoginService;

    @PostMapping
    @Operation(summary = "用户登录")
    //1:用户登录
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户登录：{}微信授权码",userLoginDTO.getCode());
        User user = userLoginService.WxLogin(userLoginDTO);
        //1：为微信用户生成jwt令牌
        Map<String, Object> clamis = new HashMap<>();
        clamis.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtils.generateToken(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), clamis);
        //封装返回的对象
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setToken(token);
        userLoginVO.setOpenid(user.getOpenid());
        return Result.success(userLoginVO);
    }
}
